package com.coolw.dynamic.thread.pool.context;

import org.dromara.hutool.core.text.StrUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 默认线程池工厂
 *
 * @author coolw
 * @date 2024/5/21 16:40
 */
public class DefaultThreadFactory implements ThreadFactory {

    /**
     * 线程池名称前缀
     */
    private final String namePrefix;

    /**
     * 是否守护线程
     */
    private Boolean deamon;

    /**
     * 线程优先级
     */
    private Integer priority;

    /**
     * 未捕获异常处理器
     */
    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;

    /**
     * 线程创建计数
     */
    private final AtomicLong count = new AtomicLong();

    /**
     * 默认线程名前缀
     */
    private static final String DEFAULT_NAME_PREFIX = "coolw-thread-";

    public DefaultThreadFactory() {
        this(DEFAULT_NAME_PREFIX);
    }

    public DefaultThreadFactory(String namePrefix) {
        this.namePrefix = StrUtil.isBlank(namePrefix) ? DEFAULT_NAME_PREFIX : namePrefix + "-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        if (null != namePrefix) {
            thread.setName(namePrefix + count.getAndIncrement());
        }
        if (null != deamon) {
            thread.setDaemon(deamon);
        }
        if (null != priority) {
            thread.setPriority(priority);
        }
        if (null != uncaughtExceptionHandler) {
            thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
        }
        return thread;
    }
}
